
import React, { useState, useEffect } from 'react'
import { Card, Row, Col, Statistic, Table, Avatar, Tag, Button, Progress, Badge, Space } from 'antd'
import { 
  PieChartOutlined, 
  UserOutlined, 
  BookOutlined, 
  MessageOutlined, 
  ShoppingCartOutlined, 
  FileTextOutlined,
  BellOutlined,
  PlusOutlined,
  ClockCircleOutlined,
  SyncOutlined,
  EnvironmentOutlined
} from '@ant-design/icons'
import { mockApi } from '@/services/mockData'
import { useNavigate } from 'react-router-dom'

const AdminDashboard: React.FC = () => {
  const [userInfo, setUserInfo] = useState<any>(null)
  const [statistics, setStatistics] = useState<any>(null)
  const [pendingTasks, setPendingTasks] = useState<any[]>([])
  const [recentActivities, setRecentActivities] = useState<any[]>([])
  const [latestUsers, setLatestUsers] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const navigate = useNavigate()

  useEffect(() => {
    // 检查用户登录状态和权限
    const storedUserInfo = localStorage.getItem('userInfo') || sessionStorage.getItem('userInfo')
    if (!storedUserInfo) {
      navigate('/login')
      return
    }
    
    const parsedUserInfo = JSON.parse(storedUserInfo)
    setUserInfo(parsedUserInfo)
    
    // 检查是否为管理员
    if (!parsedUserInfo.isAdmin) {
      navigate('/user-dashboard')
      return
    }
    
    fetchData()
  }, [navigate])

  const fetchData = async () => {
    setLoading(true)
    try {
      // 获取统计数据
      const stats = await mockApi.getStatisticData()
      setStatistics({
        ...stats,
        totalUsers: 1580,
        activeToday: 256,
        contentViews: 12500,
        pendingReviews: 18
      })
      
      // 模拟待办任务
      const tasksData = [
        {
          id: '1',
          title: '审核新发布的资讯',
          description: '有5篇新的乡村政策资讯需要审核',
          priority: 'high',
          dueDate: '2024-03-17'
        },
        {
          id: '2',
          title: '处理用户投诉',
          description: '3个用户投诉需要处理',
          priority: 'medium',
          dueDate: '2024-03-18'
        },
        {
          id: '3',
          title: '更新平台数据',
          description: '更新市场价格数据和政策信息',
          priority: 'low',
          dueDate: '2024-03-20'
        }
      ]
      setPendingTasks(tasksData)
      
      // 模拟最近活动
      const activitiesData = [
        {
          id: '1',
          user: '张三',
          action: '发布了新文章',
          target: '《2024年春季种植指南》',
          time: '10分钟前',
          avatar: '张'
        },
        {
          id: '2',
          user: '李四',
          action: '报名了活动',
          target: '春季农业技术推广会',
          time: '30分钟前',
          avatar: '李'
        },
        {
          id: '3',
          user: '王五',
          action: '评论了文章',
          target: '《农产品电商销售技巧》',
          time: '1小时前',
          avatar: '王'
        },
        {
          id: '4',
          user: '管理员',
          action: '审核通过了文章',
          target: '《乡村旅游发展前景》',
          time: '2小时前',
          avatar: '管'
        }
      ]
      setRecentActivities(activitiesData)
      
      // 模拟最新用户
      const usersData = [
        {
          id: '1',
          username: '赵六',
          role: '普通用户',
          village: '幸福村',
          registerTime: '2024-03-16 10:30',
          status: 'active'
        },
        {
          id: '2',
          username: '钱七',
          role: '普通用户',
          village: '和平村',
          registerTime: '2024-03-16 09:15',
          status: 'active'
        },
        {
          id: '3',
          username: '孙八',
          role: '普通用户',
          village: '民主村',
          registerTime: '2024-03-15 16:45',
          status: 'pending'
        },
        {
          id: '4',
          username: '周九',
          role: '普通用户',
          village: '团结村',
          registerTime: '2024-03-15 14:20',
          status: 'active'
        },
        {
          id: '5',
          username: '吴十',
          role: '普通用户',
          village: '友谊村',
          registerTime: '2024-03-14 11:50',
          status: 'inactive'
        }
      ]
      setLatestUsers(usersData)
    } catch (error) {
      console.error('获取数据失败:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleLogout = () => {
    // 清除登录状态
    localStorage.removeItem('userInfo')
    sessionStorage.removeItem('userInfo')
    navigate('/login')
  }

  // 快捷管理操作处理函数
  const handleQuickAction = (actionName: string) => {
    const actionMap: { [key: string]: string } = {
      '用户管理': '/admin/users',
      '内容审核': '/admin/content-review',
      '政策发布': '/admin/policy-publish',
      '市场数据管理': '/admin/market-data',
      '活动管理': '/admin/activity-management',
      '社群管理': '/admin/community-management',
      '数据统计': '/admin/statistics',
      '系统设置': '/admin/system-settings',
      '媒体融合管理': '/admin/media-integration',
      '乡村服务管理': '/admin/rural-service',
      '数字治理管理': '/admin/digital-governance',
      '乡村建设管理': '/admin/digital-rural-construction'
    }
    
    const route = actionMap[actionName]
    if (route) {
      navigate(route)
    } else {
      console.warn(`未找到对应路由: ${actionName}`)
    }
  }

  // 用户表格的列定义
  const userColumns = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username'
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role'
    },
    {
      title: '所属村庄',
      dataIndex: 'village',
      key: 'village'
    },
    {
      title: '注册时间',
      dataIndex: 'registerTime',
      key: 'registerTime'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        let color = 'default'
        let text = status
        
        switch (status) {
          case 'active':
            color = 'green'
            text = '活跃'
            break
          case 'pending':
            color = 'orange'
            text = '待审核'
            break
          case 'inactive':
            color = 'red'
            text = '未活跃'
            break
          default:
            color = 'default'
        }
        
        return <Tag color={color}>{text}</Tag>
      }
    },
    {
      title: '操作',
      key: 'action',
      render: () => (
        <Space size="middle">
          <Button type="link" size="small">详情</Button>
          <Button type="link" size="small">编辑</Button>
        </Space>
      )
    }
  ]

  // 内容分类数据
  const contentTypes = [
    { name: '政策资讯', value: 35 },
    { name: '技术指导', value: 25 },
    { name: '市场分析', value: 20 },
    { name: '乡村文化', value: 15 },
    { name: '其他', value: 5 }
  ]

  return (
    <div style={{ 
      minHeight: '100vh', 
      background: '#f0f2f5', 
      width: '100%', 
      padding: 0,
      position: 'relative',
      zIndex: 1,
      marginLeft: 0 // 移除margin，避免与外部布局冲突
    }}>
      {/* 管理员头部 */}
      <div style={{
        background: 'linear-gradient(135deg, #1890ff 0%, #096dd9 100%)',
        padding: '20px 24px',
        color: 'white',
        boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
        position: 'relative',
        zIndex: 10
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <h1 style={{ margin: 0, fontSize: 24 }}>乡村产业发展平台 - 管理中心</h1>
            <p style={{ margin: '4px 0 0 0', opacity: 0.9, fontSize: 14 }}>欢迎您，管理员 - {userInfo?.username || ''}</p>
          </div>
          
          <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            <Badge count={3} showZero>
              <Button 
                type="text" 
                icon={<BellOutlined />} 
                style={{ color: 'white' }}
              >
                通知
              </Button>
            </Badge>
            
            <Button 
              onClick={handleLogout}
              style={{ 
                background: 'rgba(255,255,255,0.2)',
                borderColor: 'rgba(255,255,255,0.3)',
                color: 'white'
              }}
            >
              退出登录
            </Button>
          </div>
        </div>
      </div>

      {/* 主体内容 - 完全避开侧边栏 */}
      <div style={{ 
        padding: '24px',
        width: '100%', // 使用100%宽度，因为App.tsx已经为侧边栏预留了空间
        boxSizing: 'border-box',
        position: 'relative', // 使用相对定位
        zIndex: 100 // 提高z-index确保在侧边栏之上
      }}>
        {/* 统计卡片 - 修复响应式布局问题 */}
        <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
          <Col xs={24} sm={12} md={6} xl={6}>
            <Card 
              hoverable 
              style={{
                height: '100%',
                borderRadius: '8px', 
                border: 'none',
                boxShadow: '0 2px 8px rgba(0,0,0,0.08)',
                background: 'linear-gradient(135deg, #1890ff 0%, #096dd9 100%)',
                color: 'white'
              }}
            >
              <Statistic
                title="总用户数"
                value={statistics?.totalUsers || 0}
                prefix={<UserOutlined />}
                valueStyle={{ color: 'white' }}
                suffix={` (今日新增: ${statistics?.activeToday || 0})`}
              />
            </Card>
          </Col>
          
          <Col xs={24} sm={12} md={6} xl={6}>
            <Card 
              hoverable 
              style={{
                height: '100%',
                borderRadius: '8px', 
                border: 'none',
                boxShadow: '0 2px 8px rgba(0,0,0,0.08)',
                background: 'linear-gradient(135deg, #52c41a 0%, #389e0d 100%)',
                color: 'white'
              }}
            >
              <Statistic
                title="内容浏览量"
                value={statistics?.contentViews || 0}
                prefix={<BookOutlined />}
                valueStyle={{ color: 'white' }}
                suffix={` (本周: ${Math.round((statistics?.contentViews || 0) * 0.3)})`}
              />
            </Card>
          </Col>
          
          <Col xs={24} sm={12} md={6} xl={6}>
            <Card 
              hoverable 
              style={{
                height: '100%',
                borderRadius: '8px', 
                border: 'none',
                boxShadow: '0 2px 8px rgba(0,0,0,0.08)',
                background: 'linear-gradient(135deg, #faad14 0%, #d48806 100%)',
                color: 'white'
              }}
            >
              <Statistic
                title="待审核内容"
                value={statistics?.pendingReviews || 0}
                prefix={<ClockCircleOutlined />}
                valueStyle={{ color: 'white' }}
                suffix={` (紧急: ${Math.round((statistics?.pendingReviews || 0) * 0.4)})`}
              />
            </Card>
          </Col>
          
          <Col xs={24} sm={12} md={6} xl={6}>
            <Card 
              hoverable 
              style={{
                height: '100%',
                borderRadius: '8px', 
                border: 'none',
                boxShadow: '0 2px 8px rgba(0,0,0,0.08)',
                background: 'linear-gradient(135deg, #722ed1 0%, #531dab 100%)',
                color: 'white'
              }}
            >
              <Statistic
                title="活跃社群数"
                value={38}
                prefix={<MessageOutlined />}
                valueStyle={{ color: 'white' }}
                suffix={` (在线: ${12})`}
              />
            </Card>
          </Col>
        </Row>

        {/* 数据概览和待办任务 */}
        <Row gutter={[24, 24]}>
          {/* 内容分布和平台活跃度 */}
          <Col xs={24} lg={16}>
            <Row gutter={[16, 16]}>
              <Col xs={24} md={12}>
                <Card 
                  title="内容分类分布"
                  style={{ 
                    borderRadius: '8px', 
                    border: 'none',
                    boxShadow: '0 2px 8px rgba(0,0,0,0.08)' 
                  }}
                  extra={<Button type="link">详情</Button>}
                >
                  <div style={{ height: '220px', display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
                    {contentTypes.map((item, index) => (
                      <div key={index} style={{ marginBottom: '12px' }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
                          <span style={{ fontSize: '14px', color: '#333' }}>{item.name}</span>
                          <span style={{ fontSize: '14px', fontWeight: 500, color: '#1890ff' }}>{item.value}%</span>
                        </div>
                        <Progress percent={item.value} strokeColor={`hsl(${index * 45}, 70%, 50%)`} strokeWidth={6} showInfo={false} />
                      </div>
                    ))}
                  </div>
                </Card>
              </Col>
              
              <Col xs={24} md={12}>
                <Card 
                  title="平台活跃度趋势"
                  style={{ 
                    borderRadius: '8px', 
                    border: 'none',
                    boxShadow: '0 2px 8px rgba(0,0,0,0.08)' 
                  }}
                  extra={<Button type="link">详情</Button>}
                >
                  <div style={{ height: '220px', display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
                    {/* 模拟图表数据 */}
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', height: '180px' }}>
                      {['周一', '周二', '周三', '周四', '周五', '周六', '周日'].map((day, index) => {
                        const height = Math.floor(Math.random() * 80) + 20
                        return (
                          <div key={index} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                            <div 
                              style={{
                                width: '24px',
                                height: `${height}%`,
                                backgroundColor: '#1890ff',
                                borderRadius: '4px 4px 0 0',
                                marginBottom: '8px'
                              }}
                            />
                            <span style={{ fontSize: '12px', color: '#666' }}>{day}</span>
                          </div>
                        )
                      })}
                    </div>
                  </div>
                </Card>
              </Col>
            </Row>

            {/* 最新用户列表 */}
            <Card 
              title="最新用户" 
              style={{ 
                borderRadius: '8px', 
                border: 'none',
                boxShadow: '0 2px 8px rgba(0,0,0,0.08)',
                marginTop: '16px' 
              }}
              extra={<Button type="link">查看全部</Button>}
            >
              <Table
                loading={loading}
                dataSource={latestUsers}
                columns={userColumns}
                pagination={false}
                rowKey="id"
                size="small"
              />
            </Card>
          </Col>

          {/* 待办任务和最近活动 */}
          <Col xs={24} lg={8}>
            <Card 
              title="待办任务" 
              style={{ 
                borderRadius: '8px', 
                border: 'none',
                boxShadow: '0 2px 8px rgba(0,0,0,0.08)' 
              }}
              extra={<Button type="primary" size="small" icon={<PlusOutlined />}>添加任务</Button>}
            >
              <div style={{ maxHeight: '300px', overflowY: 'auto' }}>
                {pendingTasks.map(task => (
                  <div 
                    key={task.id} 
                    style={{
                      padding: '12px',
                      marginBottom: '12px',
                      borderRadius: '8px',
                      backgroundColor: '#fafafa',
                      borderLeft: `4px solid ${task.priority === 'high' ? '#ff4d4f' : task.priority === 'medium' ? '#faad14' : '#52c41a'}`
                    }}
                  >
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
                      <h4 style={{ margin: 0, fontSize: '14px', fontWeight: 500 }}>{task.title}</h4>
                      {task.priority === 'high' && (
                        <Tag color="red">紧急</Tag>
                      )}
                      {task.priority === 'medium' && (
                        <Tag color="orange">中等</Tag>
                      )}
                      {task.priority === 'low' && (
                        <Tag color="green">一般</Tag>
                      )}
                    </div>
                    <p style={{ margin: 0, fontSize: '12px', color: '#666', marginBottom: '8px' }}>{task.description}</p>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <span style={{ fontSize: '12px', color: '#999' }}>截止日期: {task.dueDate}</span>
                      <Button type="link" size="small">处理</Button>
                    </div>
                  </div>
                ))}
              </div>
            </Card>

            {/* 最近活动 */}
            <Card 
              title="最近活动" 
              style={{ 
                borderRadius: '8px', 
                border: 'none',
                boxShadow: '0 2px 8px rgba(0,0,0,0.08)',
                marginTop: '24px' 
              }}
              extra={<Button type="link" size="small">查看全部</Button>}
            >
              <div style={{ maxHeight: '300px', overflowY: 'auto' }}>
                {recentActivities.map(activity => (
                  <div 
                    key={activity.id} 
                    style={{
                      padding: '12px 0',
                      borderBottom: '1px solid #f0f0f0',
                      display: 'flex',
                      alignItems: 'center',
                      gap: '12px'
                    }}
                  >
                    <Avatar style={{ backgroundColor: '#1890ff' }}>{activity.avatar}</Avatar>
                    <div style={{ flex: 1 }}>
                      <p style={{ margin: 0, fontSize: '14px', color: '#333' }}>
                        <span style={{ fontWeight: 500 }}>{activity.user}</span>
                        {' '}{activity.action}{' '}
                        <span style={{ color: '#1890ff' }}>{activity.target}</span>
                      </p>
                      <p style={{ margin: '4px 0 0 0', fontSize: '12px', color: '#999' }}>{activity.time}</p>
                    </div>
                  </div>
                ))}
              </div>
            </Card>
          </Col>
        </Row>

        {/* 快捷管理操作 */}
        <Card 
          title="快捷管理操作" 
          style={{ 
            borderRadius: '8px', 
            border: 'none',
            boxShadow: '0 2px 8px rgba(0,0,0,0.08)',
            marginTop: '24px' 
          }}
        >
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: '16px' }}>
            {[
              { name: '用户管理', icon: <UserOutlined />, color: '#1890ff' },
              { name: '内容审核', icon: <FileTextOutlined />, color: '#faad14' },
              { name: '政策发布', icon: <BookOutlined />, color: '#52c41a' },
              { name: '市场数据管理', icon: <ShoppingCartOutlined />, color: '#722ed1' },
              { name: '活动管理', icon: <ClockCircleOutlined />, color: '#ff7a45' },
              { name: '社群管理', icon: <MessageOutlined />, color: '#f5222d' },
              { name: '数据统计', icon: <PieChartOutlined />, color: '#13c2c2' },
              { name: '系统设置', icon: <SyncOutlined />, color: '#595959' },
              { name: '媒体融合管理', icon: <FileTextOutlined />, color: '#eb2f96' },
              { name: '乡村服务管理', icon: <ShoppingCartOutlined />, color: '#fa541c' },
              { name: '数字治理管理', icon: <PieChartOutlined />, color: '#a0d911' },
              { name: '乡村建设管理', icon: <EnvironmentOutlined />, color: '#2f54eb' }
            ].map((item, index) => (
              <Button
                key={index}
                onClick={() => handleQuickAction(item.name)}
                style={{
                  height: '80px',
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  justifyContent: 'center',
                  backgroundColor: 'white',
                  border: '1px solid #f0f0f0',
                  borderRadius: '8px',
                  boxShadow: '0 2px 4px rgba(0,0,0,0.04)'
                }}
              >
                <div style={{ fontSize: '24px', color: item.color, marginBottom: '8px' }}>
                  {item.icon}
                </div>
                <span style={{ color: '#333' }}>{item.name}</span>
              </Button>
            ))}
          </div>
        </Card>
      </div>
    </div>
  )
}

export default AdminDashboard